import 'package:flutter/material.dart';
import 'package:helloworld/res/depositData.dart';
import 'package:helloworld/res/incomeData.dart';
import 'package:dio/dio.dart';
import 'package:loading/loading.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';
import 'dart:ui';
import 'package:date_format/date_format.dart';

class Deposit extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Deposit();
  }
}

class _Deposit extends State<Deposit> with WidgetsBindingObserver {
  int _index;
  int flag = 1;
  Color _color;
  Color _loadColor;
  Color _depositColor;
  Color _textColor;
  Color _boxColor;
  Color _depositItemColor;
  Future<Null> _refresh() async {
    setState(() {
      flag = 1;
      depositData.clear();
    });
    await getTotalIncome();
    await _getData();
    return;
  }

  _getData() async {
    Response response =
        await Dio().get("http://123.207.114.127:1314/deposit/selectAll");
    Response res = await Dio().post(
        "http://123.207.114.127:1314/income/selectByDate",
        queryParameters: {
          'incomemonth': '${formatDate(incomeDate, [mm])}',
          'incomeyear': '${formatDate(incomeDate, [yyyy])}'
        });
    double _totalIncome = 0;
    for (int i = 0; i < res.data.length; i++) {
      _totalIncome = _totalIncome + res.data[i]['income'];
    }
    totalIncome = _totalIncome;
    setState(() {
      if (response.data.length == 0) {
        flag = 0;
      }
      depositData = response.data;
    });
  }

  @override
  void didChangePlatformBrightness() {
    // TODO: implement didChangePlatformBrightness
    super.didChangePlatformBrightness();
    if (window.platformBrightness == Brightness.dark) {
      _color = Colors.black45;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _depositColor = Colors.white;
      _boxColor = Colors.grey;
      _depositItemColor = Colors.greenAccent;
    } else {
      _color = Colors.lightBlueAccent;
      _loadColor = Colors.lightBlue;
      _textColor = Colors.black54;
      _depositColor = Colors.black54;
      _boxColor = Colors.black26;
      _depositItemColor = Colors.blue;
    }
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
    var bool = ModalRoute.of(context).isCurrent;
    if (bool) {
      _getData();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    if (window.platformBrightness == Brightness.dark) {
      _color = Colors.black45;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _depositColor = Colors.white;
      _boxColor = Colors.grey;
      _depositItemColor = Colors.greenAccent;
    } else {
      _color = Colors.lightBlueAccent;
      _loadColor = Colors.lightBlue;
      _textColor = Colors.black54;
      _depositColor = Colors.black54;
      _boxColor = Colors.black26;
      _depositItemColor = Colors.blue;
    }
    _getData();
    // getTotalIncome();
  }

  Widget loadingData() {
    if (depositData.length == 0 && flag == 1) {
      return Container(
          child: Center(
        child: Loading(
            indicator: BallPulseIndicator(), size: 100.0, color: _loadColor),
      ));
    } else if (depositData.length == 0 && flag == 0) {
      return Container(
          child: Center(
        child: ListView(
          children: <Widget>[
            SizedBox(
              height: 200,
            ),
            Center(
              child: Text(
                '暂无存款信息',
                style: TextStyle(color: _textColor, fontSize: 30),
              ),
            )
          ],
        ),
      ));
    } else {
      return ListView(
        physics: AlwaysScrollableScrollPhysics(),
        children: depositData.asMap().keys.map((f) {
          return Column(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                    border: Border.all(width: 1, color: _boxColor),
                    borderRadius: BorderRadius.circular(15)),
                child: ListTile(
                  leading: Icon(
                    Icons.monetization_on,
                    size: 40,
                  ),
                  title: Text(depositData[f]['depositcount']),
                  subtitle: Text(depositData[f]['depositnumber']),
                  trailing: Text(
                    depositData[f]['deposit'].toStringAsFixed(2),
                    style: TextStyle(
                      fontSize: 15,
                    ),
                  ),
                  selected: f == _index,
                  onTap: () {
                    setState(() {
                      _index = f;
                      Navigator.pushNamed(context, '/depositDetail',
                          arguments: {'id': _index});
                    });
                  },
                ),
              ),
              SizedBox(
                height: 10,
              )
            ],
          );
        }).toList(),
      );
    }
  }

  Widget loadingTotal() {
    if (depositData.length == 0) {
      return Text(
        '0.00',
        style: TextStyle(color: _depositColor, fontSize: 40),
      );
    } else {
      return myDeposit(depositData, _depositColor);
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        SizedBox(
          height: 10,
        ),
        Padding(
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
            child: Center(
              child: Column(
                children: <Widget>[
                  Text(
                    '存款',
                    style: TextStyle(color: _textColor),
                  ),
                  loadingTotal(),
                  Padding(
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Center(
                            child: Container(
                              child: FlatButton(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    // Icon(Icons.attach_money,color: Colors.white,size: 22,),
                                    // SizedBox(width: 10,),
                                    Text(
                                      '${formatDate(incomeDate, [
                                        mm,
                                      ])}月收入：',
                                      style: TextStyle(
                                          fontSize: 14, color: _textColor),
                                    ),
                                    // SizedBox(width: 10,),
                                    Text(
                                      '+' + totalIncome.toStringAsFixed(2),
                                      style: TextStyle(
                                          fontSize: 15, color: _depositColor),
                                    ),
                                  ],
                                ),
                                onPressed: () {
                                  Navigator.pushNamed(context, '/inCome');
                                },
                              ),
                              height: 55,
                            ),
                          ),
                          flex: 1,
                        ),
                        Expanded(
                          child: Container(
                            height: 30,
                            width: 1,
                            decoration: BoxDecoration(
                                border: Border.all(color: _boxColor)),
                          ),
                          flex: 0,
                        ),
                        Expanded(
                          child: Center(
                            child: Container(
                              child: FlatButton(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(
                                      Icons.add,
                                      color: _textColor,
                                    ),
                                    SizedBox(
                                      width: 10,
                                    ),
                                    Text(
                                      '添加存款',
                                      style: TextStyle(
                                          fontSize: 15, color: _textColor),
                                    ),
                                  ],
                                ),
                                onPressed: () {
                                  Navigator.pushNamed(context, '/addDeposit');
                                },
                              ),
                              height: 55,
                            ),
                          ),
                          flex: 1,
                        ),
                      ],
                    ),
                    padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                  ),
                ],
              ),
            ),
            width: double.infinity,
            //128 iphone11
            // height: 138,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20),
                color: _color,
                boxShadow: [
                  // BoxShadow(
                  //     color: Colors.black12,
                  //     offset: Offset(0.0, 5.0), //阴影xy轴偏移量
                  //     blurRadius: 15.0, //阴影模糊程度
                  //     spreadRadius: 1.0 //阴影扩散程度
                  //     )
                ]),
          ),
          padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
        ),
        SizedBox(
          height: 10,
        ),
        Expanded(
          child: Container(
            padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
            child: RefreshIndicator(
              displacement: 20,
              child: loadingData(),
              onRefresh: _refresh,
            ),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}

class myDeposit extends StatelessWidget {
  double _debtCount = 0;
  Color _depositColor;
  myDeposit(List depositData, Color depositColor) {
    _depositColor = depositColor;
    for (int i = 0; i < depositData.length; i++) {
      _debtCount = _debtCount + depositData[i]['deposit'];
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Text(
      _debtCount.toStringAsFixed(2),
      style: TextStyle(color: _depositColor, fontSize: 40),
    );
  }
}
